﻿package de.gameduell.framework.facebook.app.appevents {
	import de.gameduell.framework.facebook.app.Controller;
	import de.gameduell.framework.facebook.app.GameData;

	import de.gameduell.framework.debug.Debug;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class CoinTriggeredAction extends EventDispatcher {

		private var _triggerValue:int;
		private var _eventName:String;
		private var _active:Boolean;
		private var _controller:Controller;

		public function CoinTriggeredAction(aController:Controller, eventXMl:XML){
			_triggerValue = int(eventXMl.@triggerValue);
			_eventName = String(eventXMl.@eventName);
			_controller = aController;
			_controller.gameData.addEventListener(GameData.APP_INIT_DONE, initEvent);
		}
		
		private function initEvent(event:Event):void {
			_controller.gameData.removeEventListener(GameData.APP_INIT_DONE, initEvent);
			_active = _controller.gameData.coins < _triggerValue;
			if(_active){
				_controller.gameData.addEventListener(GameData.APP_COINS_CHANGED, checkEvent);
			}
			Debug.trace("CoinEvent::initEvent: " + _triggerValue + ":" + _eventName + ":" + _active);
		}
		
		private function checkEvent(event:Event):void {
			if(_active){
				if(_controller.gameData.coins >= _triggerValue){
					_active = false;
					_controller.gameData.removeEventListener(GameData.APP_COINS_CHANGED, checkEvent);
					Debug.trace("CoinEvent::checkEvent: EVENT STARTED: " + _triggerValue + ":" + _eventName);
					dispatchEvent(new CoinEvent(CoinEvent.COIN_EVENT_STARTED, this));
				}
			}
		}
		
		public function get triggerValue():int {
			return _triggerValue;
		}
		
		public function get active():Boolean {
			return _active;
		}
		
		public function get eventName():String {
			return _eventName;
		}
	}
}
